<template>
  <div class="mailbox-add">
    <el-page-header @back="goBack" :title="getPageTitle()"></el-page-header>
    
    <div class="form-container">
      <el-form 
        ref="mailboxForm" 
        :model="formData" 
        :rules="rules" 
        label-width="120px"
        :disabled="isView"
      >
        <el-form-item label="提交人" prop="owner.id">
          <el-select v-model="formData.owner.id" placeholder="请选择提交人" style="width: 100%" @change="handleOwnerChange">
            <el-option v-for="owner in ownerOptions" :key="owner.id" :label="owner.name" :value="owner.id"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="formData.contact" placeholder="请输入联系电话" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
            <el-option label="建议" value="建议"></el-option>
            <el-option label="咨询" value="咨询"></el-option>
            <el-option label="投诉" value="投诉"></el-option>
            <el-option label="表扬" value="表扬"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="formData.content" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入内容"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="提交时间" prop="submitTime">
          <el-date-picker
            v-model="formData.submitTime"
            type="datetime"
            placeholder="选择提交时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="未读" value="未读"></el-option>
            <el-option label="已读" value="已读"></el-option>
            <el-option label="已回复" value="已回复"></el-option>
          </el-select>
        </el-form-item>
        
        <template v-if="isReply || formData.status === '已回复'">
          <el-divider content-position="center">回复信息</el-divider>
          
          <el-form-item label="处理人" prop="handlerName">
            <el-input v-model="formData.handlerName" placeholder="请输入处理人姓名"></el-input>
          </el-form-item>
          
          <el-form-item label="回复内容" prop="replyContent">
            <el-input 
              v-model="formData.replyContent" 
              type="textarea" 
              :rows="4" 
              placeholder="请输入回复内容"
            ></el-input>
          </el-form-item>
          
          <el-form-item label="回复时间" prop="replyTime">
            <el-date-picker
              v-model="formData.replyTime"
              type="datetime"
              placeholder="选择回复时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </template>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" v-if="!isView" :loading="loading">保存</el-button>
          <el-button @click="goBack">{{ isView ? '返回' : '取消' }}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ElMessage } from 'element-plus';
import axios from 'axios';

export default {
  name: 'MailboxAdd',
  data() {
    return {
      isEdit: false,
      isView: false,
      isReply: false,
      formData: {
        id: null,
        owner: {
          id: null,
          name: ''
        },
        title: '',
        content: '',
        type: '',
        status: '未读',
        submitTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
        replyTime: null,
        replyContent: '',
        handlerName: '',
        contact: ''
      },
      ownerOptions: [],
      loading: false,
      rules: {
        'owner.id': [{ required: true, message: '请选择提交人', trigger: 'change' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        handlerName: [{ required: true, message: '请输入处理人姓名', trigger: 'blur' }],
        replyContent: [{ required: true, message: '请输入回复内容', trigger: 'blur' }]
      }
    };
  },
  created() {
    // 加载业主选项
    this.fetchOwners();
    
    const id = this.$route.query.id;
    const view = this.$route.query.view;
    const reply = this.$route.query.reply;
    
    if (id) {
      this.isEdit = true;
      if (view === 'true') {
        this.isView = true;
      }
      if (reply === 'true') {
        this.isReply = true;
      }
      this.fetchMailboxData(id);
    }
  },
  methods: {
    // 获取业主列表
    fetchOwners() {
      axios.get('/api/owners')
        .then(response => {
          let owners = [];
          if (Array.isArray(response.data)) {
            owners = response.data;
          } else if (response.data && Array.isArray(response.data.content)) {
            owners = response.data.content;
          }
          
          // 确保每个业主对象都有必要的字段
          this.ownerOptions = owners.map(owner => ({
            id: owner.id,
            name: owner.name,
            phoneNumber: owner.phoneNumber || owner.phone || ''
          }));
        })
        .catch(error => {
          console.error('获取业主列表失败:', error);
          ElMessage.error('获取业主列表失败');
        });
    },
    
    // 处理业主选择变更
    handleOwnerChange(ownerId) {
      const selectedOwner = this.ownerOptions.find(owner => owner.id === ownerId);
      if (selectedOwner) {
        this.formData.owner.name = selectedOwner.name;
        // 自动填充联系方式
        if (selectedOwner.phoneNumber) {
          this.formData.contact = selectedOwner.phoneNumber;
        }
      }
    },
    
    getPageTitle() {
      if (this.isView) {
        return '查看信箱';
      } else if (this.isReply) {
        return '回复信箱';
      } else if (this.isEdit) {
        return '编辑信箱';
      } else {
        return '添加信箱';
      }
    },
    
    fetchMailboxData(id) {
      this.loading = true;
      axios.get(`/api/mailboxes/${id}`)
        .then(response => {
          const data = response.data;
          
          // 确保owner对象存在
          if (!data.owner) data.owner = { id: null, name: '' };
          
          this.formData = {
            id: data.id,
            owner: {
              id: data.owner.id,
              name: data.owner.name || ''
            },
            title: data.title || '',
            content: data.content || '',
            type: data.type || '',
            status: data.status || '未读',
            submitTime: data.submitTime ? this.formatDateTime(data.submitTime) : null,
            replyTime: data.replyTime ? this.formatDateTime(data.replyTime) : null,
            replyContent: data.replyContent || '',
            handlerName: data.handlerName || '',
            contact: data.owner?.phoneNumber || ''
          };
          
          this.loading = false;
        })
        .catch(error => {
          console.error('获取信箱信息失败:', error);
          ElMessage.error('获取信箱信息失败');
          this.loading = false;
        });
    },
    
    formatDateTime(dateTimeStr) {
      if (!dateTimeStr) return null;
      const date = new Date(dateTimeStr);
      if (isNaN(date.getTime())) return null;
      
      return date.toISOString().slice(0, 19).replace('T', ' ');
    },
    
    submitForm() {
      this.$refs.mailboxForm.validate(valid => {
        if (valid) {
          this.loading = true;
          
          // 构建提交数据 - 按照后端API需要的格式
          const submitData = {
            id: this.formData.id,
            owner: {
              id: this.formData.owner.id
            },
            title: this.formData.title,
            content: this.formData.content,
            type: this.formData.type,
            status: this.formData.status,
            submitTime: this.formData.submitTime ? new Date(this.formData.submitTime).getTime() : new Date().getTime(),
            handlerName: this.formData.handlerName || null,
            replyContent: this.formData.replyContent || null
          };
          
          // 如果是已回复状态，设置回复时间
          if (this.formData.status === '已回复') {
            submitData.replyTime = this.formData.replyTime ? 
              new Date(this.formData.replyTime).getTime() : 
              new Date().getTime();
          }
          
          console.log('提交的数据:', submitData); // 调试日志
          
          if (this.isEdit) {
            // 更新信箱信息
            axios.put(`/api/mailboxes/${submitData.id}`, submitData)
              .then(() => {
                ElMessage.success('更新信箱信息成功');
                this.goBack();
              })
              .catch(error => {
                console.error('更新信箱信息失败:', error);
                ElMessage.error('更新信箱信息失败: ' + (error.response?.data?.message || error.message));
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            // 新增信箱信息
            axios.post('/api/mailboxes', submitData)
              .then(() => {
                ElMessage.success('新增信箱信息成功');
                this.goBack();
              })
              .catch(error => {
                console.error('新增信箱信息失败:', error);
                ElMessage.error('新增信箱信息失败: ' + (error.response?.data?.message || error.message));
              })
              .finally(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    
    goBack() {
      this.$router.push('/property/service/mailbox');
    }
  }
};
</script>

<style scoped>
.mailbox-add {
  padding: 20px;
}
.form-container {
  margin-top: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 
